package com.zr.lads.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.zr.lads.dao.FuncDao;
import com.zr.lads.dao.RoleDao;
import com.zr.lads.pojo.Role;
import com.zr.lads.service.RoleService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * 角色功能service层实现类
 * @author tang
 *
 */
@Repository("roleService")
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleDao<Role> roleDao;
	@Resource
	private FuncDao<String> funcDao;
	
	@Override
	public JSONObject getAllRoles(int start, int pageSize) {
		List<Role> roles = roleDao.getAllRoles(start, pageSize);
		for (Role role : roles) {
			role.setRoleFuncs(funcDao.getFuncsNameByIds(role.getRoleFuncs()));
		}
		int count = roleDao.getAllRolesCount();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", count);
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"users"});
		jsonObject.put("rows", JSONArray.fromObject(roles,config));
		return jsonObject;
	}

	@Override
	public String getRoleFuncsByRoleId(int roleId) {
		Role role = roleDao.get(Role.class, roleId);
		return role.getRoleFuncs();
	}

	@Override
	public boolean updateRoleFunc(int roleId, int[] funcs) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < funcs.length; i++) {
			if (i == 0) {
				sb.append(funcs[i]);
			} else {
				sb.append(",");
				sb.append(funcs[i]);
			}
		}
		return roleDao.updateRoleFunc(roleId, sb.toString());
	}
	
}
